<template>
  <div class="form-layout form-layout4">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor :itemList="cpItemList" />
    </div>
    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="cpPropRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <template v-if="cpisClosed">
            <div id="box-close" class="box-title">作废信息</div>
            <customFormItem label="作废原因" name="closedReason" :parent="_self" :form="form" fullWidth/>
          </template>

          <div id="box-base" class="box-title">发货信息</div>
          <customFormItem label="要求送达时间" name="gmtRequireLatestDelivery" :parent="_self" :form="form" :type="constCommon.formItemType.datePicker.name" />
          <customFormItem label="发货单号" name="code" :parent="_self" :form="form"
                          :type="constCommon.formItemType.staticHtml.name"  :config="{defaultValue: '自动获取'}"/>
          <customFormItem label="采购单号" name="poCode" :parent="_self" :form="form" disabled/>
          <customFormItem label="医院" name="hospitalName" :parent="_self" :form="form" ref="hospitalId" disabled/>
          <customFormItem label="供应商" name="supplierName" :parent="_self" :form="form" disabled v-if="!utils.isSp()"/>
          <customFormItem label="需求科室" name="demandDeptName" :parent="_self" :form="form" v-show="strings.isNotBlank(form.demandDeptName)" disabled/>

          <customFormItem label="创建时间" name="gmtCreate" :parent="_self" :form="form" disabled />
          <customFormItem label="需求时间" name="purchaseDate" :parent="_self" :form="form"   v-show="strings.isNotBlank(form.purchaseDate)" disabled />

          <customFormItem
            label="订单类型"
            name="orderType"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <span  v-html="utils.getBooleanLabel(form.isConsignment,'代销', '购销')">
              </span>

              <span style="margin: 0px 5px 0px 5px" v-html="utils.getBooleanLabel(form.isOneThingOneYard,'标签管理', '非标签管理')">
              </span>

              <span v-html="utils.getDictLabel(form.materialTypeCode,constCommon.dictType.baseMatrType, '',true)">
              </span>
            </template>
          </customFormItem>
          <customFormItem label="订单金额" name="orderAmount" :parent="_self" :form="form" disabled/>
          <customFormItem label="发货金额" name="deliveryAmount" :parent="_self" :form="form" disabled/>
          <customFormItem label="需求科室" name="demandDeptName" :parent="_self" :form="form" v-show="false"/>
          <customFormItem label="发货温度" name="temperature" :parent="_self" :form="form" :type="constCommon.formItemType.inputNumber.name" v-show="3 == form.materialTypeCode"/>
          <customFormItem label="备注" name="remark" :parent="_self" :form="form" />

          <div id="box-dtl" class="box-title">发货明细 <span class="span-tip">发货明细数量多余1时可以进行拆分</span></div>
          <data-view
            propViewKey="delivery_item_crud"
            :propIsTdesign="true"
            :propDisabledActiveNext="true"
            :propParentPage="_self"
            ref="childDataView"
            :propAutoFetchData="false"
            :propTableHide="!form.id"
            propTableHideMsg="保存完主单据再添加采购明细"
            :propOnlyQueryAll="propReadonly"
            :propInitData="form"
            @edit-input="editInput"
            :propBeforeClick="propBeforeClickDtl"
            :propNoEditRow="true"
            @afterTableDataChange="afterTableDataChange"
            @extra-button-click="extraButtonClick"
            :rowEditInputValid="rowEditInputValid"
            :propGetCustomSelectStaticOption="propGetCustomSelectStaticOption"
            :propDisabledRowSaveClearActived="true"
          />

          <div id="box-more" class="box-title">物流信息</div>
          <customFormItem label="发货人" name="sendUser" :parent="_self" :form="form" disabled/>
          <customFormItem label="发货联系电话" name="sendMobile" :parent="_self" :form="form" disabled/>
          <customFormItem label="发货地址" name="sendAddress" :parent="_self" :form="form" disabled/>
          <customFormItem label="物流公司" name="logcName" :parent="_self" :form="form"/>
          <customFormItem label="物流单号" name="logcCode" :parent="_self" :form="form"/>
          <customFormItem label="物流单号" name="logcCode" :parent="_self" :form="form"/>
          <customFormItem label="预计最早送达" name="gmtExceptedEarliestDelivery" :parent="_self" :form="form" :type="constCommon.formItemType.datePicker.name" />
          <customFormItem label="预计最晚送达" name="gmtExceptedLatestDelivery" :parent="_self" :form="form" :type="constCommon.formItemType.datePicker.name" />

          <customFormItem
            label="收货仓库"
            name="warehouseName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.hospitalWarehouse(warehouseNameSelect, form.hospitalId)"
            help="保存后不可修改"
          />
          <customFormItem label="收货人" name="receiveUser" :parent="_self" :form="form" disabled/>
          <customFormItem label="收货联系电话" name="receivePhone" :parent="_self" :form="form" disabled/>
          <customFormItem label="收货地址" name="receiveAddress" :parent="_self" :form="form" disabled/>
        </template>
      </customForm>
    </div>

    <!--发货明细导入-->
    <customDrawer title="发货明细导入" ref="customDrawerImportDtl" :widthPx="500" :heightPx="500"  hideConfirm>
      <template #content>
          <dataImportArea :config="cpAreaConfig" @success="importSuccess"/>
      </template>
    </customDrawer>

    <!--发货明细拆分-->
    <customDrawer title="发货明细拆分" ref="customDrawerSplitDtl" :widthPx="500" :heightPx="400" @confirm="splitDtlConfirm" :autoHide="false">
      <template #content>
        <customForm :data="splitFormData"  ref="splitForm" >
          <template #content>
            <customFormItem  label="商品名称" name="materialName"   :parent="_self" :form="splitFormData" disabled/>
            <customFormItem  label="规格" name="materialSpec"   :parent="_self" :form="splitFormData" disabled/>
            <customFormItem  label="应发" name="shouldDeliveryQty"   :parent="_self" :form="splitFormData" disabled/>
            <customFormItem  label="发货数量" name="deliveryNumber"   :parent="_self" :form="splitFormData" disabled/>
            <customFormItem  label="拆分行数" name="qtyDtl"   :parent="_self" :form="splitFormData"   :type="constCommon.formItemType.inputNumber.name"
                 :config="{min: 1, max: splitFormData.deliveryNumber,decimalPlaces: 0}"
            />
            <small style="padding-left: 120px;">
              1、【拆分行数】不能少于发货数量，即【每行发货数量最低为1】 <br>
              2、将【发货数量】平均拆分到发货明细
            </small>
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--扫描UDI-->
    <customDrawer title="扫描UDI" ref="customDrawerScanDtl" :widthPx="600" :heightPx="400" hideConfirm>
      <template #content>
        <customSpace fullWidth style="margin-top: 9px">
          <template #content>
            <customButton  title="解析更新并关闭"  size="medium" @click="scanSave(true)" theme="primary" help="解析主码副码信息，并更新到对应发货明细中"/>
            <customButton  title="保存并关闭" size="medium" @click="scanSave(false)" theme="success" help="不解析直接以表单内容更新"/>
<!--            <customButton  title="解析" size="medium" @click="scanCheck" theme="default" help="仅解析条码信息"/>-->
          </template>
        </customSpace>
        <div>
          <FortenScan
            ref="scanInputMain"
            propMsgPrepend="主码"
            propPlaceholder="请扫描"
            propType="custom"
            :propClearAfterScan="false"
            :propEnterHandel="false"
            :propIsReplaceBracket="false"
            @after-scan="$refs.scanInputSub.focus()"
            style="width: 100%;margin-top: 10px;"/>
          <FortenScan
            ref="scanInputSub"
            propMsgPrepend="副码"
            propPlaceholder="请扫描"
            :propClearAfterScan="false"
            :propEnterHandel="false"
            :propAutofocus="false"
            :propIsReplaceBracket="false"
            propType="custom"
            style="width: 100%;margin-top: 10px;"/>
        </div>

        <customForm :data="scanDtlData"  ref="scanDtl"  :rules="scanRules" >
          <template #content>
            <div id="box-scan-box1" class="box-title">商品信息</div>
            <customFormItem  label="商品名称" name="materialName"   :parent="_self" :form="scanDtlData" disabled/>
            <customFormItem  label="规格" name="materialSpec"   :parent="_self" :form="scanDtlData" disabled/>
            <customFormItem  label="商品编码" name="materialCode"   :parent="_self" :form="scanDtlData" disabled/>
            <customFormItem  label="发货数量" name="deliveryNumber"   :parent="_self" :form="scanDtlData" disabled/>
            <customFormItem  label="UDI" name="udiSpec"   :parent="_self" :form="scanDtlData" disabled fullWidth/>

            <div id="box-scan-box1" class="box-title">解析信息</div>
            <customFormItem  label="UDI" name="UDI"   :parent="_self" :form="scanDtlData" disabled fullWidth/>
            <customFormItem  label="厂家序号" name="mfgSn"   :parent="_self" :form="scanDtlData" fullWidth/>
            <customFormItem  label="生产日期" name="productionDate"   :parent="_self" :form="scanDtlData"  :type="constCommon.formItemType.datePicker.name" />
            <customFormItem  label="效期" name="expiredDate"   :parent="_self" :form="scanDtlData"  :type="constCommon.formItemType.datePicker.name" />
            <customFormItem  label="批次" name="lot"   :parent="_self" :form="scanDtlData" />
            <small style="padding-left: 120px;font-size: 13px">
              <small>
                1、支持UDI/GTIN解析<br>
                2、可以长主码解析，也可以主码加副码解析，副码可以任意顺序<br>
                3、GS1格式 (01)产品标识DI (11)生产日期 (17)失效日期 (10)生产批号 (21)序列号<br>
                4、<span style="color: red">如果商品存在udi，则校验扫描结果udi是否一致</span><br>
              </small>
              <small>
                <span style="margin-right: 5px">UDI示例</span>(01)06901234567892(17)250505(11)220202(10)lot123(21)sn0001
                <br>
              </small>
              <small>
                <span style="margin-right: 5px">UDI示例</span>(01)06 9012345 67893(17) 250505 (11)220202(10)lot123(21)sn0001
              </small>
            </small>
          </template>
        </customForm>
      </template>
    </customDrawer>

    <!--订单明细选择-->
    <tableDrawer ref="tableDrawerOrderDtl" subtitle="仅显示未完全发货的订单明细" title="请选择订单明细"
                 :queryWrapper="cpOrderDtlQueryWrapper" refName="tableDrawerOrderDtl"
                 viewKey="purchase_order_item_crud"  loadForce
                 :widthPx="winW - 300"
        :propUserParam="{poId: form.poId}"
    />

    <snList ref="snList"/>

    <div id="printShow" style="display: none" />
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import dataImportArea from '@/views/base/help/dataImportArea.vue'
import snList from '@/views/delivery/snList.vue'
import barcodeParse from '@/util/barcodeParse.js'
import FortenPrintLabel from '@/components/common/FortenPrintLabel.vue'

export default {
  help: '发货-详情',
  data() {
    return {
      form: {},
      viewData: {},
      splitFormData: {
        qtyDtl: 1,
        deliveryNumber: 0,
      },
      scanDtlData: {
      },
      winW: window.innerWidth,
      scanRules: {
        productionDate: [{ required: true, message: '必填', trigger: 'blur' }],
        expiredDate: [{ required: true, message: '必填', trigger: 'blur' }],
      }
    }
  },
  methods: {
    // 加载明细数据
    loadDtl() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('deliveryId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },

    // 导入成功
    importSuccess() {
      this.loadDtl()
      this.afterTableDataChange()
    },

    // 仓库选择
    warehouseNameSelect(row) {
      this.$set(this.form, 'warehouseId', row.id)
      this.$set(this.form, 'warehouseName', row.name)
      this.$set(this.form, 'receiveUser', row.receiveUser)
      this.$set(this.form, 'receivePhone', row.receivePhone)
      this.$set(this.form, 'receiveAddress', row.receiveAddress)
    },

    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'deliveryNumber') { //发货数量
        //计算实发数量
        let qty = 0
        if(row.unit == row.orderUnit){
          qty = Number(row.deliveryNumber);
        }else {
          qty = Number(row.deliveryNumber) * row.orderQty
        }
        this.$set(row, 'qty', this.utilNum.toFixed(qty))
        this.$set(row, 'subtotalAmount', this.utilNum.toFixed(row.qty * row.price))
      }
    },
    // 列表添加按钮
    propBeforeClickDtl(button, formData , rowData, that) {
      //列表添加按钮 其他入库
      if (button.key == 'vb-add') {
        this.$refs.tableDrawerOrderDtl.show(this.orderDtlSelect,true)
        return false
      }
      return true;
    },
    // 批量保存明细
    orderDtlSelect(rows) {
      this.utilVue.loadShow(true)
      rows.forEach(row => {
        row.deliveryId = this.form.id
        row.poItemId = row.id
      })
      this.$ajax.put('/order/delivery_items/addBySelect', rows).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },

    // 扩展按钮事件
    extraButtonClick({button, data, index}) {
      let buttonKey = button.key
      if (buttonKey == 'importDtl') { //发货明细导入
        this.$refs.customDrawerImportDtl.show()
      } else if (buttonKey == 'splitDtl') { //发货明细拆分
        ['materialName','materialSpec','shouldDeliveryQty','deliveryNumber', 'id'].forEach(key => {
          this.$set(this.splitFormData,key,data[key])
        })
        if (this.splitFormData.deliveryNumber <= 1) {
          this.utilMessage.warning('发货数量少于1，不需要拆分')
          return
        }
        this.$set(this.splitFormData,'qtyDtl',this.splitFormData.deliveryNumber)
        this.$refs.customDrawerSplitDtl.show()
      } else if (buttonKey == 'scanDtl') { //扫描UDI
        if (this.strings.isNotBlank(data.mfgSn) && data.deliveryNumber != 1) {
          this.utilMessage.warning('该发货明细存在厂家序号，请修改发货数量为1')
          return
        }
        this.$refs.scanInputMain.clear()
        this.$refs.scanInputSub.clear()
        this.scanDtlData = JSON.parse(JSON.stringify(data))
        let setField = ['materialName','materialSpec','materialCode','udiSpec','deliveryNumber', 'id']
        setField.forEach(key => {
          this.$set(this.scanDtlData,key,data[key])
        })

        this.$refs.customDrawerScanDtl.show()
        setTimeout(() => {
          this.$refs.scanInputMain.focus()
        }, 1000)
      }
    },

    // 拆分确认
    splitDtlConfirm() {
      if (this.splitFormData.qtyDtl < 1) {
        this.utilMessage.warning('【拆分行数】小于1，不需要提交')
        return
      }
      if (this.splitFormData.qtyDtl > this.splitFormData.deliveryNumber) {
        this.utilMessage.warning('【拆分行数】超过【发货数量】，请调整')
        return
      }
      this.utilVue.loadShow(true)
      this.$ajax.post('/order/delivery_items/splitDtl', this.splitFormData).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.$refs.customDrawerSplitDtl.hide()
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },

    // udi解析
    scanCheck() {
      let valueMain = this.$refs.scanInputMain.getValue(false)
      let valueSub = this.$refs.scanInputSub.getValue(false)
      let scanValueAll = valueMain
      if (this.strings.isNotBlank(valueSub)) {
        scanValueAll+=valueSub
      }
      scanValueAll = this.strings.trim(scanValueAll)
      if (this.strings.isBlank(scanValueAll)) {
        this.utilMessage.warning('请输入主码')
        this.$refs.scanInputMain.focus()
        return false
      }
      let scanInfo = barcodeParse.gtinAnalysis(scanValueAll);
      let setMap = {}
      if (scanInfo.gtin) {
      } else if (scanInfo.udi) {
        setMap.udi = scanValueAll
        setMap.udiDi = scanInfo.udi
      } else {
        this.utilMessage.warning('标签格式暂时不支持')
        return false
      }
      if (scanInfo.expiredDate) {
        setMap.expiredDate = scanInfo.expiredDate
      }
      if (scanInfo.manufactureDate) {
        setMap.productionDate = scanInfo.manufactureDate
      }
      if (scanInfo.lot) {
        setMap.lot = scanInfo.lot
      }
      if (scanInfo.sn) {
        setMap.mfgSn = scanInfo.sn
      }
      console.log('setMap', setMap)
      if (Object.keys(setMap).length == 0) {
        return false
      }
      Object.keys(setMap).forEach( key => {
        this.$set(this.scanDtlData,key,setMap[key])
      })
      return true
    },

    // udi保存
    scanSave(isCheck) {
      if (isCheck && !this.scanCheck()) {
        return
      }
      if (this.strings.isNotBlank(this.scanDtlData.udiDi) && this.strings.isNotBlank(this.scanDtlData.udiSpec) && this.scanDtlData.udiDi != this.scanDtlData.udiSpec) {
        this.utilMessage.warning(`解析到的UDI【${this.scanDtlData.udiDi}】，与商品绑定的UDI【${this.scanDtlData.udiSpec}】不一致，请检查`)
        return
      }
      this.$refs.scanDtl.validate().then((result) => {
        if (result && result == true) {
          this._doScanSave()
        }
      })
    },
    _doScanSave() {
      let keyList = ['productionDate', 'expiredDate', 'lot', 'mfgSn']
      let setMap = {}
      keyList.forEach( key => {
        if (this.strings.isNotBlank(this.scanDtlData[key]) && this.scanDtlData[key].length > 0) {
          setMap[key] = this.scanDtlData[key]
        }
      })
      if (Object.keys(setMap).length == 0) {
        this.utilMessage.warning('厂家序号、生产日期、效期、批次至少填写一个')
        return
      }
      this.utilVue.loadShow(true)
      this.$ajax.post('/order/delivery_items/saveOrUpdateCommon', this.scanDtlData).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.$refs.customDrawerScanDtl.hide()
          this.loadDtl()
        }
      })
    },
    // 单元格输入校验
    rowEditInputValid(row, column,field, value) {
      if (field == 'deliveryNumber' && row.deliveryNumber > row.shouldDeliveryQty) {
        this.utilMessage.warning(`发货数量${row.deliveryNumber}大于应发数量${row.shouldDeliveryQty}，请检查`)
        return false
      }
      return true
    },
    // 自定义下拉框数据源
    propGetCustomSelectStaticOption(column,row) {
      // 发货单位
      if (column.name == 'orderUnit') {
        let optionList = [
          {
            label: row.unitSelect,
            value: row.unitSelect
          }
        ]
        if (row.orderUnitSelect != row.unitSelect) {
          optionList.push(
            {
              label: row.orderUnitSelect,
              value: row.orderUnitSelect
            }
          )
        }
        return optionList
      }
      return []
    },
    // 打印标签
    printLabel() {
      this.utilVue.loadShow(true)
      this.$ajax.get(`/order/delivery_item_sns/getPrintLabelData/${this.form.id}`).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          try {
            let snList = resp.data.snList

            let deliveryItemList = resp.data.deliveryItemList
            let map = new Map()
            snList.forEach(o => {
              let result = map.get(o.deliveryItemId)
              if (result == null) {
                let filtedResult = deliveryItemList.filter(t => o.deliveryItemId === t.id)
                if (filtedResult.length == 0) {
                  return
                }
                result = filtedResult[0]
                map.set(o.deliveryItemId, result)
              }

              o.materialName = result.materialName
              o.materialSpec = result.materialSpec
              o.lot = result.lot
              o.productionDate = result.productionDate
              o.manufacturerName = result.manufacturerName
              o.expiredDate = result.expiredDate
              o.orderUnit = result.orderUnit
              o.materialCode = result.materialCode
              o.flagOmoc = result.isOneThingOneYard
            })
            let param = {
              rows: snList
            }
            global.utilPrint.openLabel(param, () => {
            })
          }catch (e) {
            console.error('打印失败',e)
          }
        }
      })
    },
    // 打印表单
    printForm() {
      let token = global.utils.getToken()
      this.utilPrint.openPdfView(`打印送货单-${this.form.code}`, `${global.utils.getBaseUrlFull()}/order/deliverys/${this.form.id}/pdf-preview?X-Token=${token}`)
    },
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData) => {
        this.form = global.utils.jsonClone(formData)
        this.$set(this.form, 'id', this.form.id)
        this.loadDtl()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data) {
        let {key: buttonKey} = button
        if (buttonKey == 'printLabel') { // 打印标签
          // that.printLabel()
          that.$refs.snList.show(that.form.id)
        } else  if (buttonKey == 'printForm') { // 打印表单
          that.printForm()
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
  },
  components: { FortenPrintLabel, customAnchor, dataImportArea, snList},
  computed: {
    cpPropRules() {
      let rule = this.propRules || {}
      return rule
    },
    cpisClosed() {
      return [true,1].includes(this.form.isClosed)
    },
    cpItemList() {
      let rule = this.propRules || {}
      let itemList = [
        { name: 'box-base', title: '发货信息' },
        { name: 'box-dtl', title: '发货明细' },
        { name: 'box-more', title: '物流信息' },
      ]
      if (this.cpisClosed){
        itemList.unshift({ name: 'box-close', title: '作废信息' })
      }
      return itemList
    },
    cpAreaConfig() {
      return {
        name: 'box-1',
        title: '1、导入发货明细',
        help: `
          1、下载导入模板完善发货明细<br>
          2、导入发货明细
          `,
        downloadPath: `/order/delivery_items/downloadExcelTemp/${this.form.id}`,
        importPath: `/order/delivery_items/importDtl?deliveryId=${this.form.id}`
      }
    },
    // 订单明细选择条件
    cpOrderDtlQueryWrapper() {
      let wrapper = this.$newWrapper()
      wrapper.eq('poId',this.form.poId )
      wrapper.gt('qty - delivered_qty',0)
      wrapper.in('delivery_status',[0, 1])
      return wrapper
    }
  },
}
</script>
